package info.qingshui.browser.hk;

import java.io.File;



import info.qingshui.browser.hk.proxy.ProxySettings2;
import info.qingshui.browser.hk.setting.Setting;
import info.qingshui.browser.hk.setting.SettingActivity;
import info.qingshui.browser.hk.setting.VHostInfo;
import info.qingshui.browser.*;
import info.qingshui.browser.R;
import android.content.Intent;

import android.net.Uri;
import android.os.Bundle;

import android.util.DisplayMetrics;
import android.util.Log;
import android.webkit.*;
import android.view.*;
import android.widget.ProgressBar;

/**
 * DefaultHttpClient httpClient = new DefaultHttpClient(); HttpHost proxy = new
 * HttpHost(proxy,port);
 * httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
 * httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, new
 * UsernamePasswordCredentials("name", "pwd")); This client processes cookies
 * but does not retain them by default. To retain cookies, simply add a cookie
 * store to the HttpContext: context.setAttribute(ClientContext.COOKIE_STORE,
 * cookieStore);
 * 
 * webview 加速：http://article.un1001.com/tech/?p=9530
 */
public class HKActivity extends BaseActivity {
	public static String NAME = "HKActivity";
	
	//private Setting setting;
	private HKWebView webView;
	private ProgressBar progressBar;
	
//	GoogleAnalyticsTracker tracker;

	// 进度条相关
	private final static double progressPlus = 1.5;
	private int currentProgress = 0;
	private int otherProgress = 0;
	
	// Bundle savedInstanceState = null;
	// wv.getSettings().setBuiltInZoomControls(true); //显示放大缩小 controler
	// wv.getSettings().setSupportZoom(true); //可以缩放
	// wv.getSettings().setDefaultZoom(ZoomDensity.CLOSE);//默认缩放模式
	// 昨天设置以上无效 使用wv.setInitialScale(100);
	
	public  HKActivity() {
		super();
		this.name = NAME;
	}

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.browser);
		
		
		
		// 进度条
		progressBar = (ProgressBar) this.findViewById(R.id.progressBar);
		
		webView = (HKWebView) this.findViewById(R.id.webview);

		//检查全局配置信息
		webView.setWebChromeClient(new HKWebChromeClient(this));
		webView.setWebViewClient(new HKWebViewClient(this));
		webView.addJavascriptInterface(new JSInterface(this), "JSInterface");//JS接口
		//下载设置
		webView.setDownloadListener(new HKDownloadListener(this));
		getSetting().setWebViewDefaultSettings(webView);
		
		
		
		//获取上个界面传递的参数
		//获取到上一个页面传过来的Intent
		Intent intent=this.getIntent();
		//获取Intent中的Bundle数据
		Bundle  bl=intent.getExtras();
		String goUrl=null;
		if( bl != null ) {
			goUrl = bl.getString("go_url");
		}
		Log.d(HKActivity.class.getSimpleName()," load url go_url:" + goUrl);
		if( goUrl != null ) {
			Setting setting = this.getSetting();
			//代理设置
			if ( setting.isUseProxy() ) {
				String host = Uri.parse(goUrl).getHost();
				Log.d(HKActivity.class.getSimpleName()," load url host:" + host);
				VHostInfo vHostInfo = setting. getVhostsByHost( host );
				Log.d(HKActivity.class.getSimpleName()," load url vHostInfo:" + vHostInfo);
				if ( vHostInfo != null ) {
					vHostInfo.loadWebview(webView, setting, goUrl);
					
				} else {
					ProxySettings2.resetProxy( this.getBaseContext() );
					webView.loadUrl( goUrl );
				}
			} else {
				this.webView.loadUrl( goUrl );
			}
		} else {
			if (savedInstanceState != null) {//新启动
				restoreInstanceState( savedInstanceState);
			}
		}
		//Log.d(HKActivity.class.getSimpleName(), "onCreate");
		
		//升级提示
		//判断当前是否需要升级
		Setting setting = this.getBrowserApplication().getSetting();
		if( setting.isNeedUpdateVersion() && !setting.isRemaindedUpdate()) {
			//setting.setRemaindedUpdate(true);
			UpdateManager updateManager = new UpdateManager(setting,HKActivity.this ,setting.getUpdateDesc(), setting.getUpdateVersionUrl() );
			updateManager.checkUpdateInfo();
			
		}
		
	}


	
	private void restoreInstanceState(Bundle savedInstanceState) {
		final WebBackForwardList list = webView
		.restoreState(savedInstanceState);
		if (list != null
				&& savedInstanceState.containsKey("currentPicture")) {
			final File f = new File(
					savedInstanceState.getString("currentPicture"));
			webView.restorePicture(savedInstanceState, f);
		}

		getSetting().setWebViewDefaultSettings(webView);
		
		//Log.d(HKActivity.class.getSimpleName(), "restore ok");

	}



	private void loadIndexPage() {
//		Intent intent = new Intent();
//		intent.setClass(HKActivity.this, Main.class);
//		this.startActivity(intent);
		this.finish();
//		webView.getSettings().setCacheMode(
//				WebSettings.LOAD_DEFAULT);
//		// 加载需要显示的网页
//		webView.loadUrl(getSetting().getIndexURL());
//		Log.d(HKActivity.class.getSimpleName(), "loadIndexPage");
		// webview.loadUrl("http://wap.hao123.com/");
		//IndexManager.getIndexManager( webView.getContext() ).loadIndex(webView);
		//webView.loadUrl("template://index.html");
		//IndexManager.getIndexManager(webView.getContext()).loadIndex(webView);
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState( outState );
		savedInstanceState( outState) ;
	}
	
	/**
	 * 保存当前状态到Bundle中
	 * @param outState
	 */
	private void savedInstanceState(Bundle outState) {
		Log.d(HKActivity.class.getSimpleName(), "savedInstanceState outState=" + outState);

		// 保存当前窗口状态
		final WebBackForwardList list = webView.saveState(outState);
		File mThumbnailDir = getDir("thumbnails", 0);
		if (list != null) {
			final File f = new File(mThumbnailDir, webView.hashCode()
					+ "_pic.save");
			if (webView.savePicture(outState, f)) {
				outState.putString("currentPicture", f.getPath());
				Log.d(HKActivity.class.getSimpleName(),
						"savedInstanceState save ok :" + f.length());
			}
		}
		
		//保存设置状态
		this.getSetting().saveInstanceState( outState);
		
		Log.d(HKActivity.class.getSimpleName(), "savedInstanceState end outState=" + outState);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		/*
		 * 
		 * add()方法的四个参数，依次是： 1、组别，如果不分组的话就写Menu.NONE,
		 * 2、Id，这个很重要，Android根据这个Id来确定不同的菜单 3、顺序，那个菜单现在在前面由这个参数的大小决定
		 * 4、文本，菜单的显示文本
		 */
		menu.add(Menu.NONE, Menu.FIRST + 1, 1, getResources().getString(R.string.menu_index));
		// setIcon()方法为菜单设置图标，这里使用的是系统自带的图标，同学们留意一下,以
		// android.R开头的资源是系统提供的，我们自己提供的资源是以R开头的
		menu.add(Menu.NONE, Menu.FIRST + 2, 2, getResources().getString(R.string.menu_back) );
		menu.add(Menu.NONE, Menu.FIRST + 3, 3, getResources().getString(R.string.menu_forward));
		menu.add(Menu.NONE, Menu.FIRST + 4, 4, getResources().getString(R.string.menu_refresh));
		menu.add(Menu.NONE, Menu.FIRST + 5, 6, getResources().getString(R.string.menu_config));
		menu.add(Menu.NONE, Menu.FIRST + 7, 7, getResources().getString(R.string.common_rec));
		//menu.add(Menu.NONE, Menu.FIRST + 6, 5, getResources().getString(R.string.menu_exit));
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		//super.onOptionsItemSelected(item)
		switch (item.getItemId()) {
			case Menu.FIRST + 1:
				// 返回首页
				loadIndexPage( );
				return false;
			case Menu.FIRST + 2:
				// 后退
				goBack();
				
				return false;
			case Menu.FIRST + 3:
				// 前进
				if (webView.canGoForward()) {
					// 临时设置从cache获取数据
					webView.getSettings().setCacheMode(
							WebSettings.LOAD_CACHE_ELSE_NETWORK);
					webView.goForward();
				}
				return false;
			case Menu.FIRST + 4:

				// 刷新
				// Toast.makeText(this, "添加菜单被点击了", Toast.LENGTH_LONG).show();
				//webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
				webView.reload();
				//Toast.makeText(this, "reload ok", Toast.LENGTH_LONG).show();
				
				return false;
			case Menu.FIRST + 5:
				// 设置
				 Intent intent =new Intent(HKActivity.this,SettingActivity.class); 
				 startActivity(intent); 
				 return false;
			case Menu.FIRST + 6:
				// 退出
				// Toast.makeText(this, "发送菜单被点击了", Toast.LENGTH_LONG).show();
				//this.finish();;
				this.getBrowserApplication().exit();
				return false;
			case Menu.FIRST + 7:
				// 推荐好友
				this.rec();
				return false;
		}
		return super.onOptionsItemSelected( item);
	}



	@Override
	public void onOptionsMenuClosed(Menu menu) {
		// Toast.makeText(this, "选项菜单关闭了", Toast.LENGTH_LONG).show();
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		// Toast.makeText(this,
		// "选项菜单显示之前onPrepareOptionsMenu方法会被调用，你可以用此方法来根据打当时的情况调整菜单",
		// Toast.LENGTH_LONG).show();

		// 如果返回false，此方法就把用户点击menu的动作给消费了，onCreateOptionsMenu方法将不会被调用

		return true;

	}

	// 覆盖Activity类的onKeyDown(int keyCoder,KeyEvent event)方法
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		switch (keyCode) {
			case KeyEvent.KEYCODE_VOLUME_DOWN:
				// scrollToPageDown();
				webView.pageDown(false);
				return true;
			case KeyEvent.KEYCODE_VOLUME_UP:
				// scrollToPageUp();
				webView.pageUp(false);
				return true;
			case KeyEvent.KEYCODE_BACK:
				//后退键
				goBack();
				return true;
			default:
				super.onKeyDown(keyCode, event);
		}

		return false;
	}
	
	private void goBack() {
		if ( this.currentProgress> 0 ) {//当前有在进行的操作，则取消
			webView.stopLoading();
			progressBar.setProgress(0);
			currentProgress = 0;
			otherProgress = 0;
		} else if (webView.canGoBack()) {
			// 临时设置从cache获取数据
			webView.getSettings().setCacheMode(
					WebSettings.LOAD_CACHE_ELSE_NETWORK);
			webView.goBack();
			
			if ( webView.getUrl().equals( "about:blank") ) {
				loadIndexPage();
			}
			Log.d(HKActivity.class.getSimpleName(), "goBack can goback" + webView.getUrl());
		} else {
			loadIndexPage();
		}
	}

	/**
	 * 屏蔽部分keyup事件
	 */
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		switch (keyCode) {
			case KeyEvent.KEYCODE_VOLUME_DOWN:
				return true;
			case KeyEvent.KEYCODE_VOLUME_UP:
				return true;
			case KeyEvent.KEYCODE_BACK:
				return true;
			default:
				super.onKeyUp(keyCode, event);
		}
		return false;
	}

	/**
	 * 更新进度条
	 */
	public void updateProgress() {
		int userProgress = (int) (currentProgress * progressPlus + otherProgress);
		if (userProgress >= 100) {
			userProgress = 100;
		}
		// Toast.makeText(hkActivity, "进度"+ progress, Toast.LENGTH_LONG).show();
		// Make the bar disappear after URL is loaded, and changes string to
		// Loading...
		this.setTitle("正在加載網頁..." + userProgress + "%");

		this.setProgress(userProgress * 100); // Make the bar disappear after
												// URL is loaded
		progressBar.setProgress(userProgress * 100);
		
		// Return the app name after finish loading
		if (userProgress == 100) {
			this.setTitle(webView.getTitle());
			this.currentProgress = 0;
			this.otherProgress = 0;
			progressBar.setProgress(0);
		}
	}

	public void setCurrentProgress(int progress) {
		this.currentProgress = progress;
	}

	public int getCurrentProgress() {
		return currentProgress;
	}

	public int getOtherProgress() {
		return otherProgress;
	}

	public void setOtherProgress(int otherProgress) {
		this.otherProgress = otherProgress;
	}

	public HKWebView getWebview() {
		return webView;
	}

	/**
	 * 获得显示区高度
	 * 
	 * @return
	 */
	public int getDisplayHeight() {
		DisplayMetrics metrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metrics);
		return metrics.heightPixels - 30;

	}


	public HKWebView getWebView() {
		return webView;
	}



	public ProgressBar getProgressBar() {
		return progressBar;
	}

	private void rec() {
		Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:"));
		intent.putExtra("sms_body", getResources().getString(R.string.common_rec_content));
		startActivity(intent);
	}

}